package com.abc.tacos.controller;

import com.abc.tacos.bean.RegistrationForm;
import com.abc.tacos.dao.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;


/**
 * @author Kar
 * @create 2022-04-26 下午4:13
 */
@Controller
@RequestMapping("/register")
public class RegistrationController {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public RegistrationController(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @ModelAttribute
    public RegistrationForm registrationForm(){
        return new RegistrationForm();
    }

    @GetMapping
    public String registerForm(){
        return "registration";
    }

    @PostMapping
    public String processRegistration(@Valid RegistrationForm registrationForm, Errors errors){
        if (errors.hasErrors()){
            return "registration";
        }
        userRepository.save(registrationForm.toUser(passwordEncoder));
        return "redirect:/login";
    }

}
